package com.mingserve.raw.runner;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

/**
 * WiFi热点服务
 * 桥接模式+D-Bus挂载	网络隔离安全，支持容器间通信
 * 条件：
 * 1. 确保宿主机已安装NetworkManager和D-Bus
 * sudo apt install network-manager dbus
 * sudo systemctl is-active dbus NetworkManager
 * 2. 检查D-Bus socket文件是否存在
 * ls -l /var/run/dbus/system_bus_socket
 * 3. 容器以root运行，挂载D-Bus socket,机器ID，配置环境变量
 * 4. 检查 D-Bus 连接是否正常
 * docker exec -it your-container-name bash dbus-send --system --print-reply --dest=org.freedesktop.DBus / org.freedesktop.DBus.ListNames
 * 5. 需在 docker-compose.yml 中保持以下配置
 * volumes:
 * - /var/run/dbus/system_bus_socket:/var/run/dbus/system_bus_socket
 * - /etc/machine-id:/etc/machine-id
 * cap_add:
 * - NET_ADMIN
 */
@Service
public class HotspotService {
    /**
     * 热点接口名称
     */
    @Value("${hotspot.interface:wlp1s0}")
    private String interfaceName;

    /**
     * 热点SSID
     */
    @Value("${hotspot.ssid:Mingserve_Sensor}")
    private String ssid;

    /**
     * 热点密码
     */
    @Value("${hotspot.password:Ming@Serve}")
    private String password;

    static {
        // 确保使用容器内的D-Bus地址
        System.setProperty("DBUS_SYSTEM_BUS_ADDRESS", System.getenv().getOrDefault("DBUS_SYSTEM_BUS_ADDRESS", "unix:path=/var/run/dbus/system_bus_socket"));
    }

    /**
     * 检查热点是否激活
     *
     * @return true表示热点已激活，false表示热点未激活
     * @throws IOException          如果执行命令时发生I/O错误
     * @throws InterruptedException 如果等待命令执行时发生中断
     */
    public boolean isHotspotActive() throws IOException, InterruptedException {
        // 使用--active参数只显示活动的连接
        Process process = Runtime.getRuntime().exec("nmcli connection show --active");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = reader.readLine()) != null) {
            // 查找活动的热点连接
            if (line.toLowerCase().contains("hotspot")) {
                return true;
            }
        }

        int exitCode = process.waitFor();
        if (exitCode != 0) {
            throw new RuntimeException("Command execution failed");
        }

        return false;
    }

    /**
     * 开启热点
     *
     * @throws IOException          如果执行命令时发生I/O错误
     * @throws InterruptedException 如果等待命令执行时发生中断
     */
    public void enableHotspot() throws IOException, InterruptedException {
        // nmcli device wifi hotspot ifname wlp1s0 ssid Mingserve_Sensor password Ming@Serve
        String command = String.format("nmcli device wifi hotspot ifname %s ssid %s password \"%s\"", interfaceName, ssid, password);

        Process process = Runtime.getRuntime().exec(command);
        int exitCode = process.waitFor();

        if (exitCode != 0) {
            throw new RuntimeException("Failed to enable hotspot. Exit code: " + exitCode);
        }
    }
}
